//
//  SearchDetailsViewController.m
//  InSuger
//
//  Created by dllo on 15/11/27.
//  Copyright © 2015年 Dior_3g. All rights reserved.
//

#import "SearchDetailsViewController.h"
#import "Product.h"
#import "Topic.h"
#import "ProductCVCCell.h"
#import "sinTopicTVCell.h"
#import "SearchCollectionDetailsViewController.h"
#import "HomePageDetailViewController.h"
@interface SearchDetailsViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UITableViewDataSource, UITableViewDelegate>
@property(nonatomic, strong) NSMutableArray *topicArr;
@property(nonatomic, strong) NSMutableArray *topicClickArr;
@property(nonatomic, strong) NSMutableArray *productArr;
@property(nonatomic, strong) UIButton *leftButton;
@property(nonatomic, strong) UIButton *rightButton;
@property(nonatomic, strong) UIScrollView *scrollView;
@property(nonatomic, strong)UICollectionView *collectionView;
@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong) MBProgressHUD *progress;
@end

@implementation SearchDetailsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
    [self createScrollView];
    [self createCollectionView];
    [self createTableView];
    
    self.progress = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    _progress.labelText = @"Loading...";
    _progress.mode = MBProgressHUDModeDeterminate;
    
    [self createSearchData];
}


#pragma mark create TableView
- (void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(self.view.frame.size.width, 0.047976 * self.view.frame.size.height, self.scrollView.frame.size.width,0.853 * self.scrollView.frame.size.height) style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:self.tableView];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 150;
    self.tableView.separatorStyle = NO;
    
    @weakify(self);
    [self addColorChangedBlock:^{
        @strongify(self);
        self.navigationController.navigationBar.nightBarTintColor = UIColorFromRGB(0x444444);
        self.navigationItem.leftBarButtonItem.nightTintColor = [UIColor blackColor];
        self.navigationItem.rightBarButtonItem.nightTintColor = [UIColor blackColor];
        self.collectionView.nightBackgroundColor = UIColorFromRGB(0x343434);
        self.collectionView.normalBackgroundColor = [UIColor whiteColor];
        self.tableView.nightBackgroundColor = UIColorFromRGB(0x343434);
        self.tableView.normalBackgroundColor = [UIColor whiteColor];
        self.scrollView.nightBackgroundColor = UIColorFromRGB(0x343434);
        self.scrollView.normalBackgroundColor = [UIColor whiteColor];
        self.view.nightBackgroundColor = UIColorFromRGB(0x343434);
        self.view.normalBackgroundColor = [UIColor whiteColor];
        
    }];
}


#pragma mark TableView Delegate Method
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.topicArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *reuse = @"reuse";
    sinTopicTVCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (!cell) {
        cell = [[sinTopicTVCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuse];
    }
    [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:[self.topicArr[indexPath.row] pic]] placeholderImage:[UIImage imageNamed:@"PlaceHolder.png"]];
    NSMutableAttributedString *attrituteStr = [[NSMutableAttributedString alloc] initWithString:[self.topicArr[indexPath.row] searchResultsTitle_topic]];
    NSRange range = [[self.topicArr[indexPath.row] searchResultsTitle_topic ] rangeOfString:self.searchStr];
    [attrituteStr setAttributes:@{NSForegroundColorAttributeName:[UIColor redColor], NSFontAttributeName:[UIFont systemFontOfSize:18.0]} range:range];
    cell.titleLabel.attributedText = attrituteStr;
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([[self.topicArr[indexPath.row] topicType] isEqualToString:@"0"]){
        HomePageDetailViewController * homePageDetailsVC = [[HomePageDetailViewController alloc] init];
        homePageDetailsVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:homePageDetailsVC animated:YES];
        
        homePageDetailsVC.model = self.topicClickArr[indexPath.row];
    } else{
        NSLog(@"111");
    }
}


#pragma mark SearchResultsCollectionView Setting
- (void)createCollectionView
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(0.47333 * self.view.frame.size.width , self.view.frame.size.height / 3);
    flowLayout.minimumInteritemSpacing = 1;
    flowLayout.minimumLineSpacing = 1;
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0.047976 * self.view.frame.size.height, self.view.frame.size.width, self.view.frame.size.height * 0.8531) collectionViewLayout:flowLayout];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:self.collectionView];
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerClass:[ProductCVCCell class] forCellWithReuseIdentifier:@"productCVC"];
    
}


#pragma mark CollectionView Delegate Method
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.productArr.count - 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
        ProductCVCCell *cell = [self.collectionView dequeueReusableCellWithReuseIdentifier:@"productCVC" forIndexPath:indexPath];
        [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:[self.productArr[indexPath.row] pic]] placeholderImage:[UIImage imageNamed:@"PlaceHolder.png"]];
        cell.priceLabel.text = [NSString stringWithFormat:@"🐑%@", [self.productArr[indexPath.row] price]];
        NSMutableAttributedString *attrituteStr = [[NSMutableAttributedString alloc] initWithString:[self.productArr[indexPath.row] searchResultsTitle_product]];
        NSRange range = [[self.productArr[indexPath.row] searchResultsTitle_product ] rangeOfString:self.searchStr];
        [attrituteStr setAttributes:@{NSForegroundColorAttributeName:[UIColor redColor], NSFontAttributeName:[UIFont systemFontOfSize:18.0]} range:range];
        cell.titleLabel.attributedText = attrituteStr;
        return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    SearchCollectionDetailsViewController *searchCollectionDetailsVC = [[SearchCollectionDetailsViewController alloc] init];
    searchCollectionDetailsVC.str = [self.productArr[indexPath.row] productId];
    searchCollectionDetailsVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:searchCollectionDetailsVC animated:YES];
}


#pragma mark ScrollVIew
- (void)createScrollView
{
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    self.scrollView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.scrollView];
    
    self.scrollView.pagingEnabled = YES;
    self.scrollView.bounces = NO;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.delegate = self;
    self.scrollView.contentSize = CGSizeMake(2 * self.view.frame.size.width, 0);
    
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).with.offset(0);
        make.right.equalTo(self.view.mas_right).with.offset(0);
        make.top.equalTo(self.view.mas_top).with.offset(0);
        make.bottom.equalTo(self.view.mas_bottom).with.offset(0);
    }];
   
    [self setButton];

}


#pragma mark ScrollView Delegate Method
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (self.scrollView.contentOffset.x == 0) {
        self.leftButton.backgroundColor = [UIColor cyanColor];
        self.rightButton.backgroundColor = [UIColor whiteColor];
    } else {
        self.rightButton.backgroundColor = [UIColor cyanColor];
        self.leftButton.backgroundColor = [UIColor whiteColor];
    }
}


#pragma Top Button
- (void)setButton
{
    self.leftButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [_leftButton addTarget:self action:@selector(Button:) forControlEvents:UIControlEventTouchUpInside];
    [_leftButton setTitle:@"单品" forState:UIControlStateNormal];
    [self.view addSubview:_leftButton];
    _leftButton.backgroundColor = [UIColor cyanColor];
    
    self.rightButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [_rightButton addTarget:self action:@selector(Button:) forControlEvents:UIControlEventTouchUpInside];
    [_rightButton setTitle:@"专题" forState:UIControlStateNormal];
    [self.view addSubview:_rightButton];
    
    [self.leftButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.left.equalTo(self.view.mas_left).with.offset(0);
        make.right.equalTo(self.rightButton.mas_left).with.offset(0);
        make.top.equalTo(self.view.mas_top).with.offset(0);
        make.height.mas_equalTo(30);
        make.width.equalTo(self.rightButton);
    }];
    [self.rightButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.left.equalTo(self.leftButton.mas_right).with.offset(0);
        make.top.equalTo(self.view.mas_top).with.offset(0);
        make.right.equalTo(self.view).with.offset(0);
        make.width.equalTo(self.leftButton);
        make.height.equalTo(self.leftButton);
    }];
}


#pragma mark Button Click Method
- (void)Button:(UIButton *)sender
{
    if (sender == self.leftButton) {
        self.scrollView.contentOffset = CGPointMake(0, 0);
        self.leftButton.backgroundColor = [UIColor cyanColor];
        self.rightButton.backgroundColor = [UIColor whiteColor];
    } else {
        self.scrollView.contentOffset = CGPointMake(self.view.frame.size.width, 0);
        self.rightButton.backgroundColor = [UIColor cyanColor];
        self.leftButton.backgroundColor = [UIColor whiteColor];
    }
}


#pragma mark Search Data
- (void)createSearchData
{
     NSString *searchUrl = [NSString stringWithFormat:@"http://open3.bantangapp.com/base/search/initData?app_installtime=1445332782.662591&app_versions=4.3&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&keyword=%@&oauth_token=bf8be334eb1fd06b1bf65f5883dd415a&os_versions=9.1&track_device_info=iPhone72C1&track_deviceid=2F83AC09-B470-4C43-9DEE-E0FB95B4B438&track_user_id=1457891&v=7", [self.searchStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSLog(@"_____________%@", searchUrl);
    [AFN getdataWithString:searchUrl block:^(id block) {
        NSDictionary *dic = block;
        if ([dic[@"data"][@"topic"]count] == 0) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"无效搜索" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *ok = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
            [alert addAction:ok];
            [self presentViewController:alert animated:YES completion:nil];
        } else {
            self.productArr = [NSMutableArray array];
            self.topicArr = [NSMutableArray array];
            self.productArr = [Product baseModelByArr:dic[@"data"][@"product"]];
            self.topicArr = [Topic baseModelByArr:dic[@"data"][@"topic"]];
            self.topicClickArr = [HomePageTableViewModel baseModelByArr:dic[@"data"][@"topic"]];
            
            [self.collectionView reloadData];
            [self.tableView reloadData];
            self.progress.hidden = YES;
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
